package com.tilaiedu.mvc.config;

import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.filter.HiddenHttpMethodFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

import javax.servlet.Filter;
import javax.servlet.MultipartConfigElement;
import javax.servlet.ServletRegistration;
import java.io.File;

/**
 * @Author xlzhang
 * @Date 2022/5/25 9:31
 * @Version 1.0
 * @Description TODO
 */
public class WebInit extends AbstractAnnotationConfigDispatcherServletInitializer {
    @Override
    protected Class<?>[] getRootConfigClasses() {
        // 加载根容器的配置类
        return new Class[]{SpringConfig.class};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        // 加载mvc配置类，初始化SpringMVC容器
        return new Class[]{SpringMvcConfig.class};
    }

    @Override
    protected String[] getServletMappings() {
        // 配置dispatchServlet的拦截规则
        //  /拦截所有，但是jsp默认放行    /* 所有包括jsp
        return new String[]{"/"};
    }

    @Override
    protected Filter[] getServletFilters() {
        // 设置请求的字符编码，不设置时请求参数中有中文会乱码
        CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter();
        encodingFilter.setEncoding("UTF-8");
        // 创建一个隐藏域过滤器
        HiddenHttpMethodFilter httpMethodFilter = new HiddenHttpMethodFilter();

        return new Filter[]{encodingFilter,httpMethodFilter};
    }

    @Override
    protected void customizeRegistration(ServletRegistration.Dynamic registration) {
        // 临时文件的路径
        String location = "c://temp";
        File file = new File(location);
        if(!file.exists() && !file.isDirectory()){
            final boolean mkdir = file.mkdir();
        }
        // 上传参数
        long maxFileSize = 1024*1024*20; //20M
        long maxRequestSize = 1024*1024*40;  //40M
        // 设置文件缓存的临界点,超过则先保存到临时目录
        int fileSizeThreshold = 0;

        //配置对multipart的支持
        MultipartConfigElement multipartConfigElement =
                new MultipartConfigElement(location, maxFileSize, maxRequestSize, fileSizeThreshold);

        registration.setMultipartConfig(multipartConfigElement);

        //设置404异常处理的参数，即有404异常时让DispatchServlet抛出throwExceptionIfNoHandlerFound
        registration.setInitParameter("throwExceptionIfNoHandlerFound","true");
    }
}
